﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Diagnostics;

namespace WAVE
{
    public partial class Form1 : Form
    {
        SerialPort myPort = new SerialPort();
        Xbee myXbee = new Xbee();
        String pricer;
        String priceFromWeb;//the actual priceTextBox in string form "0.12611" or something like it
        
        public Form1()
        {
            InitializeComponent();
            int i = 0;
            while (i < 100000)
                ;
            PCUCSendPrice();
            myPort.PortName = "COM5";
        }

        public void OpenCloseComPort_Click(object sender, EventArgs e)
        {
            if (!myPort.IsOpen)
            {
                try //handles the cases when you try to connect but the xbee is not plugged in 
                {
                    myPort.PortName = CurrentComPort.Text;
                    myPort.Open();
                    CurrentComPort.Text = myPort.PortName;
                    CurrentComPort.Enabled = false;//can't change the name of the port if it is open. 
                    ComStatusIndicator.BackColor = Color.LawnGreen;
                    OpenCloseComPort.Text = "ClosePort";

                }
                catch (IOException)
                {
                    MessageBox.Show("Sorry Your Port is not available,\n Please Check your Connections");
                }
                catch (System.ArgumentException Exception)
                {
                    MessageBox.Show("Please Enter a Valid Port Name{0}", Exception.ToString());
                }
            }
            else
            {
                myPort.Close();
                ComStatusIndicator.BackColor = Color.Red;
                CurrentComPort.Enabled = true;
                OpenCloseComPort.Text = "OpenPort";
            }
        }

        public void myPort_DataReceived(object sender, EventArgs e)
        {
            //while (sender != 7E)
            //    ;

            MessageBox.Show("Wave.myPort_DataRecieved method is called");
        }

        private void nodeDiscoveryButton_Click(object sender, EventArgs e)
        {
            myXbee.buildNodeDiscoveryPacket();
            foreach (byte segment in myXbee.NDPacket)
            {
                myPort.Write(Convert.ToString(segment));   
            }
        }

        private void display_graph_Click(object sender, EventArgs e)
        {
            if(this.overlap.Checked == true)
                    Process.Start(@"D:\WAVE\GnuplotEntry.DEM");
            else if(this.sep_graphs.Checked == true)
                    Process.Start(@"D:\WAVE\GnuplotEntrySep.DEM");
        }

        private void update_Price_Click(object sender, EventArgs e)
        {
            PCUCSendPrice();
        }

//        private void CurrentComPort_TextChanged(object sender, KeyPressEventArgs e)
//        {
//           if (e.KeyChar == (char)Keys.Return)
//                sender = true;
//        }
        public void PCUCSendPrice()//*******need to handle not connected to internet case. ****%%
        {
            try
            {
                string weEnergiesWebsiteHTML = DownloadHTMLPage("http://www.we-energies.com/residential/acctoptions/wi_pricetariff.htm");
                int index = weEnergiesWebsiteHTML.IndexOf(@"Energy charge:</strong> $"); //this indexing thing doesn't seem to work
                priceFromWeb = weEnergiesWebsiteHTML.Substring(index + 25, 7);
                priceTextBox.Text = priceFromWeb;
            }
            catch (SystemException Exception)
            {
                //This exception is handled in the DownloadHTMLPage code.  
            }
        }
        /// <summary>
        /// Function to download HTML web page
        /// </summary>
        /// <param name="_URL">URL address to download web page</param>
        /// <returns>HTML contents as a string</returns>
        public string DownloadHTMLPage(string _URL)
        {
            string _PageContent = null;
            try
            {
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);   
                // Request response:
                System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();
                // Open data stream:
                System.IO.Stream _WebStream = _WebResponse.GetResponseStream();
                // Create reader object:
                System.IO.StreamReader _StreamReader = new System.IO.StreamReader(_WebStream);
                // Read the entire stream content:
                _PageContent = _StreamReader.ReadToEnd();
                // Cleanup
                _StreamReader.Close();
                _WebStream.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                MessageBox.Show("Exception caught in process: {0}", _Exception.ToString());
                return null;
            }
            return _PageContent;
        }
    }
}
